﻿using System.Windows;
using System.Windows.Controls;
using Gavel.Common.Component.Extension;

namespace Gavel.Common.Component.Controls;

/// <summary>
/// 折叠面板
/// </summary>
public class CollapsePanel : HeaderedContentControl
{
    /// <summary>
    /// 静态构造绑定默认样式
    /// </summary>
    static CollapsePanel() => DefaultStyleKeyProperty.OverrideDefaultStyle<CollapsePanel>();

    /// <summary>
    /// 是否折叠
    /// </summary>
    public static readonly DependencyProperty IsExpandedProperty = nameof(IsExpandedProperty).Register<CollapsePanel, bool>(false);

    /// <summary>
    /// 是否折叠
    /// </summary>
    public bool IsExpanded
    {
        get => (bool)GetValue(IsExpandedProperty);
        set => SetValue(IsExpandedProperty, value);
    }

    /// <summary>
    /// 标题
    /// </summary>
    public static readonly DependencyProperty TitleProperty = nameof(TitleProperty).Register<CollapsePanel, string>();

    /// <summary>
    /// 标题
    /// </summary>
    public string Title
    {
        get => (string)GetValue(TitleProperty);
        set => SetValue(TitleProperty, value);
    }

    /// <summary>
    /// 重写模板应用事件
    /// 绑定折叠面板点击事件
    /// </summary>
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        // 绑定面板内容高度
        if (GetTemplateChild("ContentPresenter") is ContentPresenter presenter)
        {
            // 强制测量内容高度
            presenter.Measure(new Size(ActualWidth, double.PositiveInfinity));
            presenter.Height = IsExpanded ? presenter.DesiredSize.Height : 0;
        }

        // 绑定折叠面板头点击事件
        if (GetTemplateChild("DockPanelTitle") is DockPanel panel)
        {
            panel.MouseLeftButtonDown += (_, _) =>
            {
                IsExpanded = !IsExpanded;
                VisualStateManager.GoToState(this, IsExpanded ? "Expanded" : "Collapsed", false);
            };
        }

        VisualStateManager.GoToState(this, IsExpanded ? "Expanded" : "Collapsed", false);
    }
}